function Animator(duration, progress) {
	this.duration = duration;
	this.progress = progress;
	this.next = true;
}
Animator.prototype = {
	constructor: Animator,
	start: function(finished) {
		var startTime = new Date().getTime();
        var duration = this.duration, self = this, timeOut = 0;            
        var vendors = ["webkit", "moz"];
        for(var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i){
        	window.requestAnimationFrame = window[vendors[i] + "RequestAnimationFrame"];
        }
        if (!window.requestAnimationFrame) {
           window.requestAnimationFrame = function (callback, element) {
				var start = 0, finish = 0;
				window.setTimeout(function () {
					start = +new Date();
					callback(start);
					finish = +new Date();
					timeOut = 1000 / 300 - (finish - start);
				}, timeOut);
           };
        }
      	window.requestAnimationFrame(function step(){
	        var p = (new Date().getTime() - startTime) / duration;
	        //var y = p * p * p;
	        self.progress(p, p);
	        if(p >= 1.0){
	        	self.progress(1.0, 1.0);
	          	self.next = false;
	          	finished();
	        }	        
	        if(self.next) window.requestAnimationFrame(step);
    	});
	},
	stop: function() {
		this.next = false;
	}
};

var Play = {
	rtspTest: "http://61.liuxianan.cn/media/xihuanni.mp4",
	videoCode: "",
	mpid: Epg.getParam("mpid", "default"),
	mode: "listRandomForever",								// 列表永久随机播放
	getPlayPlatform: function() {
		var playPlatform = CONFIG.PLATFORM;
		if(CONFIG.DOMYBOX === Epg.cookie.get("CHANNEL_CODE")){
			playPlatform = CONFIG.PLATFORM_2;
		}
		return playPlatform;
	},
	play: function() {										// 当前首播放完成后,随机播放节目单中的一首视频
		isEnableButton = false;								// 视频初始化完成,标识按钮点击可生效
		var postData = {
			userid: Home.userid, role: Home.role, mp: Play.programId.toString(), position: Math.floor(Math.random()*Play.programLength)
		};
		Epg.postAPI('mp/'+Epg.getParam('cmd','play'), postData, Play.playSuccessHandler, Play.playErrorHandler);
	},
	playFromProgram: function(programId) {					// 根据节目单ID获取节目单信息
		Play.programId = programId;
		var postData = {
			programId: programId, code: "", enablePrevNext: false,
			userid: Home.userid, role: Home.role,
			mp: programId.toString(), mode: Epg.getParam("mode", this.mode),
			cachable: true, dolog: false
		};
		var postData2 = {
			userid: Home.userid,mode:'listRandomForever', role: Home.role, mp: programId.toString()
		};
		var cmd = Epg.getParam("cmd", "play");
		var flag = programId > 0;
		Epg.postAPI('mp/'+(flag?'play-from-program':cmd), flag?postData:postData2, this.playSuccessHandler, this.playErrorHandler);
	},
	playErrorHandler: function(info){
		isEnableButton = true;				// 视频初始化完成,标识按钮点击可生效
		Epg.tip(info || "获取播放信息失败,请稍后再试!");		
	},
	playSuccessHandler: function(data) {
		if(data && data.code === 0) {
			Play.videoCode = data.mp.current.code;
			Play.programLength = Object.keys(data.mp.videoListMap).length;	// 节目单中有多少个视频
			G('recommend_video_txt').innerHTML = '正在播放: ' + data.mp.current.name;
			var postData = {
				code: Play.videoCode, appVersion: CONFIG.APP_VERSION,
				platform: Play.getPlayPlatform(), format: CONFIG.FORMAT
			};
			Epg.postAPI("mp/get-playurl", postData, function(data){
				if(data && data.code === 0 && data.playurl) {
					Play.startPlay(data.playurl);
				}
			}, Play.playErrorHandler);
		}else {
			Play.playErrorHandler();
		}
	},
	startPlay: function(url) {
		if(url) this.rtsp = url;
		this.getMD5Url(this.rtsp);
		if(CONFIG.DEBUG_MODE && this.rtspTest) this.rtsp = this.rtspTest;
		Epg.Mp.init(true);
		Epg.Mp.smallvodPlay(Play.rtsp, 26, 311, 330, 186);
		setTimeout(this.addVodLog, 3000);
		setTimeout(function() {
			isEnableButton = true;				// 视频初始化完成,标识按钮点击可生效
		}, 200);
	},
	getMD5Url: function(playurl){			// 播放地址加密,请求需要同步，async: false
		var _this = this;
		var postData = {"playurl": playurl, "domainName": "cdn.anhui-ggly-yidong.vas.lutongnet.com"};
		var jStr = "";
		for(var item in postData){
			jStr += '"'+item+'":"'+postData[item]+'",';
		}
		jStr = "{" + jStr.slice(0, -1) + "}";
		Epg.ajax({
			url: CONFIG.API_URL + "mp/alibaba-playurl",
			type: "POST", async: false, dataType: "json",
			contentType: "application/json", data: jStr,
			success: function(data){
				if(data && data.code === 0){
					_this.rtsp = data.encryptPlayurl;
				}
			}
		});
	},
	addVodLog: function(){
		if(Play.videoCode){   // 获取到视频code时添加点播日志，否则后台因为code.substring(0, 4)会陷入堆栈溢出
			Epg.addVodLog(CONFIG.COLUMN_CODE, Epg.getParam('sourceType', 'column'), Play.videoCode);
		}
	},
	afterPlayEnd: function(){// 播放完以后,随机播放节目单中一个视频
		Play.play();
	}
};

//TODO
var isEnableButton = false;						// 标识按钮是否生效,用于视频初始化时防止按钮点击生效

CONFIG.COLUMN_CODE = "ggly_iptv_home";
var uri = "column/iptv_home/iptv_home" + CONFIG.EXT + "?1=1";

var animator, ipAnimator;
var recommend_big = [], recommend_big_interval;			// 保存最大推荐位的数据实属无赖,recommend_big_interval--清理定时器
var Home = {	
	userid: Epg.cookie.get("userid"),
	role: Epg.cookie.get("role"),
	orderType: Epg.cookie.get("orderType"),
	carousel_index:Epg.getParamInt("carousel_index",1),	// 大推荐位轮屏到第几个屏
	idx: 0,												// 为了推荐位滚屏到最后一屏不全时,保存最后一位推荐位排序
	navPrevButtonId: Epg.getParam('navPrevButtonId', ''),
	recommendPrevButtonId: Epg.getParam('recommendPrevButtonId', ''),
	ipPrevButtonId: Epg.getParam('ipPrevButtonId', ''),
	recommendScrollLeft: Epg.getParamInt("recommendScrollLeft", 0),	// recommend推荐位列表scrollLeft值
	spriteType: Epg.cookie.get('spriteType', ''),
	dress: Epg.cookie.get('dress', ''),
	
	create_recommend_small: function(obj, idx) {	// 两个小推荐位放在一起的推荐位
		var html = '<div>';
		html += '<div class="recommend_small_0">';
		html += 	'<div id="recommend_'+idx+'"></div>';
		html += 	'<span class="recommend_span" style="height: 228px;" data-url="'+CONFIG.EPG_PATH+obj[0].linkImageUri+'" data-epg-btn></span>';
		html +=		'<div id="recommend_'+idx+'_txt" class="recommend_txt">'+obj[0].label+'</div>';
		html += '</div>';
		html += '<div class="recommend_small_1">';
		html += 	'<div id="recommend_'+(idx+1)+'"></div>';
		html += 	'<span class="recommend_span" style="height: 172px;" data-url="'+CONFIG.EPG_PATH+obj[1].linkImageUri+'" data-epg-btn></span>';
		html +=		'<div id="recommend_'+(idx+1)+'_txt" class="recommend_txt">'+obj[1].label+'</div>';
		html += '</div>';
		html += '</div>';
		return html;
	},
	create_recommend_middle: function(obj, idx) {	// 一个推荐位放在一起的推荐位
		var html = '<div>';
		html += '<div id="recommend_'+idx+'"></div>';
		html += '<span class="recommend_span" data-url="'+CONFIG.EPG_PATH+obj[0].linkImageUri+'" data-epg-btn></span>';
		html +=	'<div id="recommend_'+idx+'_txt" class="recommend_txt">'+obj[0].label+'</div>';
		html += '</div>';
		return html;
	},
	autoPlay: function() {							// 最大推荐位进行轮播
		Home.carousel_index++;
		Home.carousel_index = Home.carousel_index >= recommend_big[0].length ? 0 : Home.carousel_index;
		var recom_big = document.querySelectorAll('.recommend_big');
		Array.prototype.slice.call(recom_big).forEach(function(value, index) {
			var span = value.getElementsByTagName('span');
			var li = value.getElementsByTagName('li');
			Array.prototype.slice.call(span).forEach(function(value, index) {
				value.className = index === Home.carousel_index ? 'recommend_big_show' : '';
			});
			Array.prototype.slice.call(li).forEach(function(value, index) {
				value.className = index === Home.carousel_index ? 'recommend_dian' : '';
			});
			value.querySelector('.recommend_txt').innerHTML = recommend_big[index][Home.carousel_index].label;
		});		
	},
	create_recommend_big: function(obj, idx) {		// 三个大的推荐位放在一起的推荐位
		var html = '<div class="recommend_big" style="width: 439px;">';
		html += 	'<div id="recommend_'+idx+'"></div>';
		for(var i = 0, length = recommend_big[0].length; i < length; i++) {
			html += '<span data-url="'+CONFIG.EPG_PATH+obj[i].linkImageUri+'" data-epg-btn class='+(i===Home.carousel_index?"recommend_big_show":"")+'></span>';
		}
		html +=		'<div id="recommend_'+idx+'_txt" class="recommend_txt" style="width: 433px;">'+obj[Home.carousel_index].label+'</div>';
		html += 	'<ul>';
		for(i = 0; i < length; i++) {
			html += '<li class='+(i===Home.carousel_index?"recommend_dian":"")+'></li>';
		}
		html += 	'</ul>';
		html += '</div>';
		return html;
	},
	init2: function() {								// 初始化推荐位方法

		var metadatas = groups[1].metadatas;
		var html = '<div class="recommends"><div class="recommend_first">';
		html += '<div id="recommend_video_txt" class="recommend_video_txt"> </div>';

		html += '<span class="recommend_span_first_0" style="width: 156px; height: 160px; background-image:url('+CONFIG.EPG_PATH+metadatas[2].linkImageUri+')"></span>';
		html += '<span class="recommend_span_first_1" style="width: 156px; height: 160px; background-image:url('+CONFIG.EPG_PATH+metadatas[3].linkImageUri+')"></span>';
		
		html += '<div id="recommend_first_0"></div>';
		html += '<div id="recommend_first_1"></div>';
		html += '<div id="recommend_video"></div>'; 

		html += '</div>';
		var idx = 0, recommend_index = 0;
		buttons.push({id:'recommend_first_0', type:metadatas[2].type, code:metadatas[2].value, up:[], down:['recommend_video'], right:'recommend_first_1',action:Home.recommendClick, 
			focusHandler:Home.recommendFocusHandler, blurHandler:Home.recommendBlurHandler, beforeMove:Home.recommendBeforeMoveHandler, focusClass:'recommend_first_0', autoDirGroup:1});
		buttons.push({id:'recommend_first_1', type:metadatas[3].type, code:metadatas[3].value, up:[], down:['recommend_video'],left:'recommend_first_0', action:Home.recommendClick, 
			focusHandler:Home.recommendFocusHandler, blurHandler:Home.recommendBlurHandler, beforeMove:Home.recommendBeforeMoveHandler, focusClass:'recommend_first_1', autoDirGroup:1});

		buttons.push({id:'recommend_video', type:metadatas[1].type, code:metadatas[1].value, up:['recommend_first_0'], down:[], action:Home.recommendClick, 
			focusHandler:Home.recommendFocusHandler, blurHandler:Home.recommendBlurHandler, beforeMove:Home.recommendBeforeMoveHandler, focusClass:'recommend_video', autoDirGroup:1});
		var obj = {};
		for(var num = 2, i = 0, length = groups.length; num < length; num++, i++) {
			metadatas = groups[num].metadatas;
			if(metadatas.length === 1) {									// 假如是一个中的推荐位
				obj = {id:'recommend_'+idx, type:metadatas[0].type, code:metadatas[0].value,left:'recommend_first_1', up:[], down:[], action:Home.recommendClick,
					focusHandler:Home.recommendFocusHandler, blurHandler:Home.recommendBlurHandler, beforeMove:Home.recommendBeforeMoveHandler, focusClass:'recommend_middle', autoDirGroup:1};
				buttons.push(obj);
				html += this.create_recommend_middle(metadatas, idx);		// 创建中等推荐位DIV样式
				idx += 1;
			}else if(metadatas.length === 2) {								// 假如是两个小的推荐位堆在一起
				obj = {id:'recommend_'+idx, type:metadatas[0].type, code:metadatas[0].value, up:[], action:Home.recommendClick,
					focusHandler:Home.recommendFocusHandler, blurHandler:Home.recommendBlurHandler, beforeMove:Home.recommendBeforeMoveHandler, focusClass:'recommend_small_0', autoDirGroup:1};
				buttons.push(obj);
				obj = {id:'recommend_'+(idx+1), type:metadatas[1].type, code:metadatas[1].value, left:['recommend_'+(idx-1), 'recommend_video'], right:['recommend_'+(idx+2)], down:[], action:Home.recommendClick,
					focusHandler:Home.recommendFocusHandler, blurHandler:Home.recommendBlurHandler, beforeMove:Home.recommendBeforeMoveHandler, focusClass:'recommend_small_1', autoDirGroup:1};
				buttons.push(obj);
				html += this.create_recommend_small(metadatas, idx);		// 创建小等推荐位DIV样式
				idx += 2;
			}else /*if(metadatas.length === 3) */{								// 假如是三个大的推荐位堆在一起
				recommend_big.push(metadatas);
				obj = {id:'recommend_'+idx, index: recommend_index, tag:'big', up:[], down:[], action:Home.recommendClick,
					focusHandler:Home.recommendFocusHandler, blurHandler:Home.recommendBlurHandler, beforeMove:Home.recommendBeforeMoveHandler, focusClass:'recommend_big', autoDirGroup:1};
				buttons.push(obj);
				html += this.create_recommend_big(metadatas, idx);			// 创建大等推荐位DIV样式
				idx += 1;
				recommend_index += 1;
			}
		}
		Home.idx = idx;
		html += '</div>';

		G("recommends").innerHTML = html;
		G("recommends").scrollLeft = Home.recommendScrollLeft;				// 初始化推荐位的scrollLeft值
	},
	recommendFocusHandler: function() {								// 推荐位获得焦点
		//if(isEnableButton == false)return;
		if('recommend_first_0' != Epg.btn.current.id && 'recommend_first_1' != Epg.btn.current.id) {
			Epg.marquee.start();
		}
		var position = G(Epg.btn.current.id).getBoundingClientRect();
		var wrapperPosition = G("recommends").getBoundingClientRect();
		var safePx = 50;
		if(position.right >= (wrapperPosition.right - 5)) {			// 如果推荐位右边被隐藏,则推荐位列表向右滚
			if(G("recommend_"+(Home.idx-1)).getBoundingClientRect().left < 2200) {
				Home.recommendScrollLeft += G("recommend_"+(Home.idx-1)).getBoundingClientRect().right+safePx-1280;
			}else {
				Home.recommendScrollLeft += (wrapperPosition.left - position.left + safePx) * -1;
			}
			Epg.addClass(G("home_wrapper"), "home_wrapper");					// 背景替换,把挖空部分补全
			G("recommends").scrollLeft = Home.recommendScrollLeft;
			//Epg.Mp.pause();											// 停止播放
			// TODO 没有办法，只能对视频进行销毁
			Epg.Mp.destroy();
			H('recommend_video_txt');
		}else if(position.left - wrapperPosition.left < 5) {		// 如果推荐位左边被隐藏,则推荐位列表向左滚
			Home.recommendScrollLeft += position.right + safePx - wrapperPosition.right;
			if(Home.recommendScrollLeft < safePx) {
				Home.recommendScrollLeft = 0;
				Epg.removeClass(G("home_wrapper"), "home_wrapper");			// 显示背景挖空部分
				// Epg.Mp.resume();									// 恢复播放
				// TODO 只能进行视频初始化了
				isEnableButton = false;									// 防止视频初始化，按钮点击生效
				Play.playFromProgram(groups[1].metadatas[1].value);		// 播放小视频内容
				S('recommend_video_txt');
			}
			G("recommends").scrollLeft = Home.recommendScrollLeft;
		}
	},
	recommendBlurHandler: function() {								// 推荐位失去焦点
		if('recommend_first_1' != Epg.btn.previous.id && 'recommend_first_0' != Epg.btn.previous.id) {
			Epg.marquee.stop();			
		}
	},
	recommendBeforeMoveHandler: function(dir, current) {			// 推荐位移动前判断事件
		if(!isEnableButton && typeof mp != 'undefined') return false;
		if("down" === dir && !(current.down && current.down.length > 0)){
			Home.recommendPrevButtonId = current.id;
			Epg.btn.set(Home.ipPrevButtonId || "ip_0");
			return false;
		}else if("up" === dir && !(current.up && current.up.length > 0)) {
			Home.recommendPrevButtonId = current.id;
			Epg.btn.set(Home.navPrevButtonId || "nav_0");
			return false;			
		}
	},
	recommendClick: function() {									// 推荐位点击事件
		if(!isEnableButton && typeof mp != 'undefined') return;									// 初始化视频时,按钮点击事件失效
		Home.updateCurrentUri();
		var id = Epg.btn.current.id, tag = Epg.btn.current.tag;
		if('big' === tag) {											// 专门对大推荐位进行处理
			var index = Epg.btn.current.index;
			Home.isOrder({type:recommend_big[index][Home.carousel_index].type, code:recommend_big[index][Home.carousel_index].value});
		}else if('recommend_video' === id){
			if("free" != Home.orderType) {
				Epg.goMP('column/mp/mp'+CONFIG.EXT+'?method=playFromProgram&pid='+Play.programId+'&code='+Play.videoCode);
			}else {
				Epg.go('column/order/order'+CONFIG.EXT+'?source='+CONFIG.COLUMN_CODE+'&code='+Play.videoCode);
			}
		}else {
			Home.isOrder({type:Epg.btn.current.type, code:Epg.btn.current.code});
		}
	},
	isOrder: function(recommend) {									// 推荐位等的判断事件
		var type = recommend.type, code = recommend.code;
		if('album' === type || 'activity' === type|| 'column' === type) {
			Home.getActivityOrAlbum(code);
		}else if('recommend_series' === type) {
			Epg.go('column/subSeries/subSeries'+CONFIG.EXT+'?code='+code);
		}else {
			if("free" != Home.orderType) {
				Epg.goMP('column/mp/mp'+CONFIG.EXT+'?method=playVideo&code='+code);
			}else {
				Epg.go('column/order/order'+CONFIG.EXT+'?source='+CONFIG.COLUMN_CODE+'&code='+code);
			}
		}
	},
	getActivityOrAlbum: function(code) {							// 进入活动或者专辑页面
		var postData = {'code':code, 'appVersion':CONFIG.APP_VERSION, 'role':Home.role};
		Epg.postAPI('epg/get', postData, function(data) {
			if(data && data.code === 0) {
				Epg.go(data.epg.path);
			}
		});
	},
	init: function() {					// 初始化IP形象DIV
		var metadatas = groups[0].metadatas;
		var length = metadatas.length > 10 ? 10 : metadatas.length;
		var html = "<div class='ips'>";
		for(var i = 0; i < (length+1); i++) {
			html += '<div id="ip_'+i+'">';
			html += '<div id="ip_'+i+'_0"></div>';
			html += '<div id="ip_'+i+'_1"></div>';
			if(i === length) {
				html += '<div id="ip_'+i+'_2" class="ip" data-url="images/ip/ip_more.png" data-epg-btn></div>';
			}else {
				html += '<div id="ip_'+i+'_2" class="ip" data-url="'+CONFIG.EPG_PATH+metadatas[i].linkImageUri+'" data-epg-btn></div>';				
			}
			html += '</div>';
			var obj = {id:'ip_'+i, action:Home.ipClick, focusHandler:Home.ipFocusHandler, blurHandler:Home.ipBlurHandler, beforeMove:Home.ipBeforeMoveHandler, autoDirGroup:0, scrollDir:'x'};
			if(i === length) {
				obj['label'] = "更多+";
			}else {
				obj['type'] = metadatas[i].type;
				obj['code'] = metadatas[i].value;
				obj['label'] = metadatas[i].label;
			}
			if(i === 0) {
				obj['left'] = ['ip_first'];
				obj['restoreScroll'] = true;
			}else {
				obj['scrollScreen'] = true;
			}
			buttons.push(obj);
		}
		html += '</div>';
console.log("IP形象DIV:::"+html);
		G("ips").innerHTML = html;
	},
	ipFocusHandler: function() {					// IP形象获得焦点		
		var id = Epg.btn.current.id;
		G(id+"_2").style.top = "37px";				// 防止IP形象错位
		G(id+"_2").style.zIndex = "1";				// 层级最高
		//Epg.addClass(G(id+"_0"), "bubble_big");		// 气泡放大效果
		G(id+"_2").style.top = "0px";
		//Epg.removeClass(G(id+"_0"), "bubble_big");
		Epg.addClass(G(id+"_0"), "ip_bubble");
		G(id+"_0").innerHTML = Epg.btn.current.label;
	},
	ipBlurHandler: function() {						//	IP形象失去焦点
		var id = Epg.btn.previous.id;
		G(id+"_2").style.top = "37px";				// 恢复IP形象原始位置
		G(id+"_2").style.zIndex = "0";				// 层级复原
		Epg.removeClass(G(id+"_0"), "ip_bubble");	// 显示气泡效果
		G(id+"_0").innerHTML = "";
		Epg.removeClass(G(id+"_1"), "yezi");
		
	},
	ipBeforeMoveHandler: function(dir, current) {	// IP形象移动前的判断事件
		if("up" === dir) {
			Home.ipPrevButtonId = current.id;
			Epg.btn.set(Home.recommendPrevButtonId || "recommend_0");
			return false;
		}
	},
	ipClick: function() {							// IP点击事件
		if(!isEnableButton && typeof mp != 'undefined') return;					// 初始化视频时,按钮点击事件失效
		var id = Epg.btn.current.id;
		// TODO 
		// 专门对精灵入口和更多推荐位进行处理
		//if('ip_first' === id || 'ip_10' === id) return;		
		Home.updateCurrentUri();
		if('ip_first' === id || 'ip_'+(groups[0].metadatas.length > 10 ? 10 : groups[0].metadatas.length) === id) {
			if('ip_first' === id) {
				if('' === Home.spriteType) {
					//Epg.Mp.pause();
					// TODO 没有办法，只能对视频进行销毁
					Epg.Mp.destroy();
					S('popup');
					Epg.btn.set('bear');
				}else {
					Epg.go('column/spriteCenter/home/home' + CONFIG.EXT + '?isPlay=true');					
				}
			}else {
				Epg.go('column/rankingList/index' + CONFIG.EXT);
			}
		}else {
			Home.isOrder({type:Epg.btn.current.type, code:Epg.btn.current.code});			
		}
	},
	navBeforeMoveHandler: function(dir, current) {	// 导航条移动前的判断事件
		if("down" === dir) {
			Home.navPrevButtonId = current.id;
			Epg.btn.set(Home.recommendPrevButtonId || "recommend_0");
			return false;
		}
	},
	navClick: function() {							// 导航条点击事件
		if(!isEnableButton && typeof mp != 'undefined') return;					// 初始化视频时,按钮点击事件失效
		var code = Epg.btn.current.code;
		if(code === CONFIG.COLUMN_CODE) return;
		Home.updateCurrentUri();
		if('ggly_iptv_area' === code) {
			location.href = CONFIG.EPG_PATH+'column/areaPage/areaPage'+CONFIG.EXT+'?source='+CONFIG.COLUMN_CODE;
		}else if('ggly_iptv_more' === code) {
			location.href = CONFIG.EPG_PATH+'column/morePage/morePage'+CONFIG.EXT+'?source='+CONFIG.COLUMN_CODE;
		}else if("nav_order" === code) {
			if("month" == Home.orderType) {
				Epg.tip('您是已订购用户，无需重复订购');
			}else{
				Epg.go('column/order/order'+CONFIG.EXT);
			}
		}else if("nav_search" === code) {
			Epg.go('column/search/search'+CONFIG.EXT);
		}else if("nav_history" === code) {
			Epg.go('history'+CONFIG.EXT+'?isPlay=true');
		}else if("nav_fav" === code) {
			Epg.go('column/fav/seriesFav'+CONFIG.EXT+'?isPlay=true');
		}else {
			location.href = CONFIG.EPG_PATH+'column/secondPage/secondPage'+CONFIG.EXT+'?code='+code+'&source='+CONFIG.COLUMN_CODE;
		}
	},
	updateCurrentUri: function() {
		CONFIG.CURRENT_URI = uri + '&navPrevButtonId='+Home.navPrevButtonId+'&recommendPrevButtonId='+Home.recommendPrevButtonId+'&ipPrevButtonId='+Home.ipPrevButtonId+
			'&recommendScrollLeft='+Home.recommendScrollLeft+'&carousel_index='+Home.carousel_index;
	},
	initAnimator: function() {						// 初始化左下角动画形象
		var len = {
			'bear_dress_0':20, 'bear_dress_1':31, 'bear_dress_2':31, 'bear_dress_3':34,
			'rabbit_dress_0':26, 'rabbit_dress_1':31, 'rabbit_dress_2':31, 'rabbit_dress_3':36
		};
		if('' === Home.dress || '' === Home.spriteType) {
			S('animators');
			G("animators").style.backgroundImage = 'url(images/ip_first.gif)';
		}else {
			H('animators');
			Home.ipLen = len[Home.dress];
			var html = '<div class="animators">';
			for(var i = 1; i <= Home.ipLen; i++) {
				html += '<div data-url="images/animator/'+Home.spriteType+'/'+Home.dress+'/'+(i<10?('0'+i):i)+'.png" data-epg-btn></div>';
			}
			html += '</div>';
			G("animators").innerHTML = html;
			G("animators").scrollTop = 0;
			G('animators').style.backgroundImage = 'url()';
			G('animator').style.backgroundImage = 'url(images/animator/'+Home.spriteType+'/'+Home.dress+'/'+Home.ipLen+'.png)';
			
			var index = 0;
			ipAnimator = new Animator(100 * Home.ipLen, function(p){
				index = Math.floor(p * Home.ipLen);
				if(index >= Home.ipLen) {
					index = 0;
				}
				G("animators").scrollTop = index * 215;
			});	
			ipAnimator.start(function() {
				H('animator');
				S('animators');
				Home.animatorStart();
			});
		}		
	},
	animatorStart: function() {						// 动画形象摆动方法
		var index = 0;
		ipAnimator = new Animator(100 * Home.ipLen, function(p) {
			index = Math.floor(p * Home.ipLen);
			if(index >= Home.ipLen) {
				index = 0;
			}
			G("animators").scrollTop = index * 215;
		});
		ipAnimator.start(function() {
			Home.animatorStart();
		});
	},
	ipSelectAction: function() {					// IP形象选择点击事件
		var id = Epg.btn.current.id;
		Home.spriteType = id;						// 当前用户选择的IP形象
		Home.dress = Home.spriteType + '_dress_0';	// 用户拥有的初始装扮
		Home.subject = 'subject_0';					// 用户拥有的初始主题
		Home.scene = 'scene_0';						// 用户拥有的初始精灵背景
		Epg.cookie.set('spriteType', Home.spriteType);
		Epg.cookie.set('dress', Home.dress);
		Epg.cookie.set('subject', Home.subject);
		Epg.cookie.set('scene', Home.scene);
		// 选择IP形象后，赠送100个金币
		Epg.postAPI('gold/updateGoldTotal', {'numValue':100, 'userId':Home.userid, 'operation':'add', 'source':CONFIG.COLUMN_CODE});
		Epg.postAPI('baby/update-parameter', {'userId':Home.userid, 'type':'all', 'spriteType':Home.spriteType,'dress':Home.dress});
		//Epg.postAPI('baby/update-parameter', {'userId':Home.userid, 'type':'spriteType', 'spriteType':Home.spriteType});
		//Epg.postAPI('baby/update-parameter', {'userId':Home.userid, 'type':'dress', 'dress':Home.dress});		
		/*Epg.postAPI('baby/update-parameter', {'userId':Home.userid, 'type':'subject', 'subject':Home.subject});
		Epg.postAPI('baby/update-parameter', {'userId':Home.userid, 'type':'scene', 'scene':Home.scene});*/
		Epg.postAPI('consumeLog/add', {'userid':Home.userid, 'type':'dress', 'value':Home.dress});
		//Epg.postAPI('consumeLog/add', {'userid':Home.userid, 'type':'subject', 'value':Home.subject});
		//Epg.postAPI('consumeLog/add', {'userid':Home.userid, 'type':'scene', 'value':Home.scene});		
		H('popup');									// 隐藏弹窗
		Home.initAnimator();						// 重新设置动画形象
		Epg.btn.set('ip_first');
		// Epg.Mp.resume();							// 恢复播放
		isEnableButton = false;									// 防止视频初始化，按钮点击生效
		Play.playFromProgram(groups[1].metadatas[1].value);		// 播放小视频内容
	}
};

var buttons = [
	{id:'ip_first', right:['ip_0'], action:Home.ipClick, beforeMove:Home.ipBeforeMoveHandler, focusClass:'ip_first', autoDirGroup:false},
	{id:'nav_order', code:'nav_order', left:['nav_7'], action:Home.navClick, beforeMove:Home.navBeforeMoveHandler, focusClass:'nav_order', autoDirGroup:3},
	{id:'nav_search', code:'nav_search', action:Home.navClick, beforeMove:Home.navBeforeMoveHandler, focusClass:'nav_search', autoDirGroup:3},
	{id:'nav_history', code:'nav_history', action:Home.navClick, beforeMove:Home.navBeforeMoveHandler, focusClass:'nav_history', autoDirGroup:3},
	{id:'nav_fav', code:'nav_fav', action:Home.navClick, beforeMove:Home.navBeforeMoveHandler, focusClass:'nav_fav', autoDirGroup:3},
	
	{id:'bear', right:'rabbit', action:Home.ipSelectAction, focusClass:'ip', autoDirGroup:false},
	{id:'rabbit', left:'bear', action:Home.ipSelectAction, focusClass:'ip', autoDirGroup:false}
];

console.log("执行力");
var navs = ['ggly_iptv_home', 'ggly_iptv_animation', 'ggly_iptv_early', 'ggly_iptv_song', 'ggly_iptv_story', 'ggly_iptv_puzzle', 'ggly_iptv_area', 'ggly_iptv_more'];
for(var i = 0, length = navs.length; i < length; i++) {
	buttons.push({id:'nav_'+i, code:navs[i], right: i===7?['nav_order']:'', action:Home.navClick, beforeMove:Home.navBeforeMoveHandler, focusClass:'nav', autoDirGroup:4});
}
	
function back() {
	if(!isEnableButton && typeof mp != 'undefined') return;
	if(G('popup').style.visibility === 'visible') {
		H('popup');
		Epg.btn.set('ip_first');
		isEnableButton = false;									// 防止视频初始化，按钮点击生效
		Play.playFromProgram(groups[1].metadatas[1].value);		// 播放小视频内容
		return;
	}else if(Home.recommendScrollLeft > 0){
		var id = Epg.btn.current.id;
		Home.recommendScrollLeft = 0;
		G('recommends').scrollLeft = 0;
		Epg.removeClass(G("home_wrapper"), "home_wrapper");		// 显示背景挖空部分
		// TODO 只能进行视频初始化了
		isEnableButton = false;									// 防止视频初始化，按钮点击生效
		Play.playFromProgram(groups[1].metadatas[1].value);		// 播放小视频内容
		S('recommend_video_txt');
		if(/^recommend_/.test(id)){
			Epg.btn.set('recommend_0');
		}
		return;
	}
	if(window.android){android.exitAPK();} 
	//Epg.go('column/exit/exit'+CONFIG.EXT);
}

// 简单的节流函数
function throttle(func, wait, mustRun) {
    var timeout,  startTime = new Date();
    return function() {
        var context = this, args = arguments, curTime = new Date();
        clearTimeout(timeout);
        // 如果达到了规定的触发时间间隔，触发 handler
        if(curTime - startTime >= mustRun){
            //func.apply(context,args);
            func();
            startTime = curTime;
        // 没达到触发间隔，重新设定定时器
        }else{
            timeout = setTimeout(func, wait);
        }
    };
};
// 实际想绑定在 scroll 事件上的 handler
function realFunc(wrapperId){
	wrapperId = wrapperId || Epg.scroll.config.wrapperId;
	var iScrollLeft = G(wrapperId).scrollLeft;
	var iClientLeft = G(wrapperId).getBoundingClientRect().left + iScrollLeft;
	var iClientRight = G(wrapperId).offsetWidth + iClientLeft;
	var btns = G(wrapperId).querySelectorAll("[data-epg-btn]");
	for(var i = 0; i < btns.length; i++) {		
		var obj = btns[i];
		// 加载过了的就不需要加载了
		if(!Epg.hasClass(obj, "loaded")) {
			var iLeft = Epg.getAbsolutePosition(obj).left;
			var iRight = iLeft + obj.offsetWidth;
			if((iLeft > iClientLeft && iLeft < iClientRight) || (iRight > iClientLeft && iRight < iClientRight)) {
				obj.style.backgroundImage = 'url('+obj.getAttribute("data-url")+')';
				Epg.addClass(obj, "loaded");				
			}			
		}
	}
}

// 实际想绑定在 scrollTop 事件上的 handler
function realFuncTop(wrapperId){
	var iScrollTop = G(wrapperId).scrollTop;
	var iClientTop = G(wrapperId).getBoundingClientRect().top + iScrollTop;
	var iClientBottom = G(wrapperId).offsetHeight + iClientTop;
	
	var iClientTop0 = iClientTop - 2 * G(wrapperId).offsetHeight;
	var iClientBottom0 = iClientBottom - 2 * G(wrapperId).offsetHeight;
	
	var iClientTop2 = iClientTop + 2 * G(wrapperId).offsetHeight;
	var iClientBottom2 = iClientBottom + 2 * G(wrapperId).offsetHeight;
	
	var btns = G(wrapperId).querySelectorAll("[data-epg-btn]");
	for(var i = 0; i < btns.length; i++) {		
		var obj = btns[i];
		// 加载过了的就不需要加载了
		if(!Epg.hasClass(obj, "loaded")) {
			var iTop = Epg.getAbsolutePosition(obj).top;
			var iBottom = iTop + obj.offsetHeight;
			if((iTop >= iClientTop && iTop <= iClientBottom) || (iBottom >= iClientTop && iBottom <= iClientBottom)) {
				obj.style.backgroundImage = 'url('+obj.getAttribute("data-url")+')';
				Epg.addClass(obj, "loaded");				
			}else if((iTop >= iClientTop0 && iTop <= iClientBottom0) || (iBottom >= iClientTop0 && iBottom <= iClientBottom0)) {
				obj.style.backgroundImage = 'url('+obj.getAttribute("data-url")+')';
				Epg.addClass(obj, "loaded");				
			}else if((iTop >= iClientTop2 && iTop <= iClientBottom2) || (iBottom >= iClientTop2 && iBottom <= iClientBottom2)) {
				obj.style.backgroundImage = 'url('+obj.getAttribute("data-url")+')';
				Epg.addClass(obj, "loaded");				
			}
		}
	}
}

window.onunload = function() {
	recommend_big_interval && clearInterval(recommend_big_interval);
	Epg.Mp && Epg.Mp.destroy();
	animator && animator.stop();
	ipAnimator && ipAnimator.stop();
};

function init() {
	Home.init();							// 初始化IP形象DIV
	Home.init2();							// 初始化推荐位DIV
	Home.initAnimator();					// 初始化精灵形象
	Epg.autoMakeBtnDir(buttons);
	Epg.btn.init([Epg.getParam('f'), 'nav_history'], buttons, '', false);

	Epg.scroll.init({wrapperId: 'ips'});
	realFunc();
	G("ips").addEventListener("scroll", throttle(realFunc, 250, 500));

	realFuncTop('animators');
	G("animators").addEventListener("scroll", throttle(function() {
		realFuncTop("animators");
	}, 250, 500));

	recommend_big_interval = setInterval(function() {
		Home.autoPlay();
	}, 4000);												// 每个4s切换大推荐位内容
	if(Home.recommendScrollLeft > 0) {
		isEnableButton = true;
	}else {
		Play.playFromProgram(groups[1].metadatas[1].value);	// 播放小视频内容
	}
}

var groups = [];
!(function() {
	window.method = "playFromProgram";
	Epg.key.init();
	Epg.key.set({
		KEY_ENTER: 'Epg.Button.click()',			//确定键
		KEY_LEFT: 'Epg.Button.move("left")',		//左键
		KEY_RIGHT: 'Epg.Button.move("right")',		//右键
		KEY_UP: 'Epg.Button.move("up")',			//上键
		KEY_DOWN: 'Epg.Button.move("down")',		//下键
		KEY_BACK: back,								//返回键
		EVENT_MEDIA_END: Play.afterPlayEnd,
		EVENT_MEDIA_ERROR: function(){
			isEnableButton = true;					// 视频初始化完成,标识按钮点击可生效
			return Epg.tip("啊哦，视频播放错误了-_-!");
		}
	});	
	Epg.key.set({
		KEY_VOL_UP: 'Epg.Mp.volUp()',
		KEY_VOL_DOWN: 'Epg.Mp.volDown()'
	});
	if(Home.recommendScrollLeft > 0) {				// 如果推荐位发生了滚动,补全空白处
		Epg.addClass(G("home_wrapper"), "home_wrapper");
	}
	Epg.postAPI("epg/get", {code:CONFIG.COLUMN_CODE, appVersion:CONFIG.APP_VERSION}, function(data) {
		if(data && data.code === 0) {
			groups = data.epg.groups;

			if(groups.length > 0) {
				init();
			}
		}
	});	
})();

